<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>表格识别系统</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        .container {
            text-align: center;
        }
        .upload-area {
            border: 2px dashed #ccc;
            padding: 20px;
            margin: 20px 0;
            border-radius: 5px;
        }
        #imagePreview {
            max-width: 100%;
            margin: 10px 0;
            display: none;
        }
        .button {
            background-color: #4CAF50;
            border: none;
            color: white;
            padding: 15px 32px;
            text-align: center;
            text-decoration: none;
            display: inline-block;
            font-size: 16px;
            margin: 4px 2px;
            cursor: pointer;
            border-radius: 4px;
        }
        .button:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }
        .tables-container {
            margin-top: 20px;
            text-align: left;
        }
        .table-wrapper {
            margin: 20px 0;
            padding: 20px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        table {
            border-collapse: collapse;
            width: 100%;
            margin: 10px 0;
        }
        th, td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }
        th {
            background-color: #f2f2f2;
        }
        .export-btn {
            background-color: #2196F3;
            margin-top: 10px;
        }
        .progress-overlay {
            position: absolute;
            bottom: 0;
            left: 0;
            height: 4px;
            background-color: rgba(255, 255, 255, 0.3);
            width: 100%;
            display: none;
        }
        .progress-bar {
            height: 100%;
            background-color: #ffffff;
            transition: width 0.3s ease;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>表格识别系统</h1>
        <div class="upload-area">
            <input type="file" id="fileInput" accept="image/*">
            <p>支持的格式: JPG, PNG, BMP</p>
        </div>
        <img id="imagePreview">
        <div class="button-container">
            <button id="recognizeBtn" class="button" style="display: none;">
                <span class="button-text">识别表格</span>
                <div class="progress-overlay" id="recognizeProgress">
                    <div class="progress-bar" style="width: 0%"></div>
                </div>
            </button>
        </div>
        <div id="tablesContainer" class="tables-container"></div>
    </div>

    <script>
        document.getElementById('fileInput').addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (!file) return;

            const preview = document.getElementById('imagePreview');
            preview.style.display = 'block';
            preview.src = URL.createObjectURL(file);
            
            document.getElementById('recognizeBtn').style.display = 'block';
            document.getElementById('tablesContainer').innerHTML = '';
        });

        function updateButtonProgress(buttonId, progressId, percent) {
            const progressOverlay = document.getElementById(progressId);
            const progressBar = progressOverlay.querySelector('.progress-bar');
            const button = document.getElementById(buttonId);
            
            if (percent > 0) {
                progressOverlay.style.display = 'block';
            }
            
            progressBar.style.width = percent + '%';
            
            const buttonText = button.querySelector('.button-text');
            buttonText.textContent = percent < 100 ? `处理中 ${percent}%` : '识别表格';
                
            if (percent >= 100) {
                setTimeout(() => {
                    progressOverlay.style.display = 'none';
                    progressBar.style.width = '0%';
                }, 1000);
            }
        }

        document.getElementById('recognizeBtn').addEventListener('click', async function() {
            const button = this;
            button.disabled = true;
            updateButtonProgress('recognizeBtn', 'recognizeProgress', 0);
            
            let progress = 0;
            const progressInterval = setInterval(() => {
                progress += Math.random() * 10;
                if (progress > 90) {
                    clearInterval(progressInterval);
                    progress = 90;
                }
                updateButtonProgress('recognizeBtn', 'recognizeProgress', Math.min(Math.round(progress), 90));
            }, 300);

            try {
                const file = document.getElementById('fileInput').files[0];
                if (!file) return;

                const formData = new FormData();
                formData.append('file', file);

                const response = await fetch('/ocr_table/', {
                    method: 'POST',
                    body: formData
                });
                
                const data = await response.json();
                
                if (data.error) {
                    throw new Error(data.error);
                }

                const tablesContainer = document.getElementById('tablesContainer');
                tablesContainer.innerHTML = '';

                if (!data.tables || data.tables.length === 0) {
                    tablesContainer.innerHTML = '<p>未检测到表格</p>';
                    return;
                }

                data.tables.forEach((table, index) => {
                    if (!table.html) {
                        console.error('Table HTML is missing for table', index);
                        return;
                    }

                    const wrapper = document.createElement('div');
                    wrapper.className = 'table-wrapper';
                    wrapper.innerHTML = `
                        <h3>表格 ${index + 1}</h3>
                        ${table.html}
                        <button class="button export-btn" onclick="exportToExcel(${index})">导出到Excel</button>
                    `;
                    tablesContainer.appendChild(wrapper);
                });

                clearInterval(progressInterval);
                updateButtonProgress('recognizeBtn', 'recognizeProgress', 100);
            } catch (error) {
                clearInterval(progressInterval);
                updateButtonProgress('recognizeBtn', 'recognizeProgress', 0);
                console.error('Error:', error);
                alert('识别失败：' + (error.message || '请重试'));
            } finally {
                button.disabled = false;
            }
        });

        function exportToExcel(tableIndex) {
            const table = document.querySelectorAll('.table-wrapper table')[tableIndex];
            if (!table) {
                console.error('Table not found');
                return;
            }

            let csvContent = '\ufeff';
            
            const rows = table.querySelectorAll('tr');
            
            for (let i = 0; i < rows.length; i++) {
                const row = [];
                const cells = rows[i].querySelectorAll('td, th');
                
                for (let j = 0; j < cells.length; j++) {
                    let cellText = cells[j].innerText.trim();
                    if (cellText.includes(',') || cellText.includes('\n') || cellText.includes('"')) {
                        cellText = `"${cellText.replace(/"/g, '""')}"`;
                    }
                    row.push(cellText);
                }
                
                csvContent += row.join(',') + '\n';
            }

            const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8' });
            
            const link = document.createElement('a');
            link.href = URL.createObjectURL(blob);
            link.download = `table_${tableIndex + 1}.csv`;
            
            document.body.appendChild(link);
            link.click();
            
            document.body.removeChild(link);
            URL.revokeObjectURL(link.href);
        }
    </script>
</body>
</html>